"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 在主节点执行failover是否成功
Create At   : 2021/01/20
Owner       : opentestcase015
Description :
    1.在主机上执行failover（主机执行，不stop备机）
    2.执行refrashconf进行信息写入
    3.重启集群
    4.检查主备状态是否正常
    5.环境恢复
Expect      :
    1.在主机上执行failover成功
    2.执行refrashconf进行信息写入成功
    3.重启集群成功
    4.检查主备状态，主备状态正常,主备切换失败
    5.成功
History     :
    Modified by opentestcase027 2023/1/13: 优化用例步骤格式及一主两备判断方式
"""

import unittest
import os
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class SystemInternalTools(unittest.TestCase):
    def setUp(self):
        LOG.info(f'--------{os.path.basename(__file__)} start--------')
        self.constant = Constant()
        self.PrimaryNode = Node('PrimaryDbUser')
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.StandbyNode = Node('Standby1DbUser')
        self.sh_standby = CommonSH('Standby1DbUser')

    def test_system_internal_tools(self):
        LOG.info('--------step1:主机执行failover   expect: 成功--------')
        excute_cmd = f"source {macro.DB_ENV_PATH};" \
                     f"gs_ctl failover -D {macro.DB_INSTANCE_PATH} -m fast"
        LOG.info(excute_cmd)
        excute_msg = self.PrimaryNode.sh(excute_cmd).result()
        LOG.info(excute_msg)
        self.assertIn(self.constant.FAILOVER_SUCCESS_MSG, excute_msg)

        LOG.info('-------step2:进行refreshconf信息写入  expect: 成功--------')
        excute_cmd = f"source {macro.DB_ENV_PATH};" \
                     f"gs_om -t refreshconf"
        LOG.info(excute_cmd)
        excute_msg = self.PrimaryNode.sh(excute_cmd).result()
        LOG.info(excute_msg)
        self.assertIn(self.constant.REFRESHCONF_SUCCESS_MSG, excute_msg)

        LOG.info('-------step3:重启集群           expect: 成功--------')
        self.sh_primary.restart_db_cluster()
        status = self.sh_primary.get_db_cluster_status()
        self.assertIn(self.constant.CLUSTER_NORMAL_MSG, status)

        LOG.info('-------step4:查看主备状态  expect:主备状态正常切换失败')
        status = self.sh_primary.get_db_cluster_status(param='detail')
        self.assertIn('P Primary Normal', status)

    def tearDown(self):
        LOG.info('--------step5:环境恢复    expect:成功---------')
        node_msg = self.sh_standby.get_db_cluster_status(param='detail')
        if 'S Primary Normal' in node_msg:
            LOG.info('--------------恢复主备状态--------------')
            recover_cmd = f'''source {macro.DB_ENV_PATH};
                gs_ctl switchover -D {macro.DB_INSTANCE_PATH} -m fast;
                gs_om -t refreshconf;
                '''
            LOG.info(recover_cmd)
            msg1 = self.PrimaryNode.sh(recover_cmd).result()
            LOG.info(msg1)
        else:
            return '主备节点正常'
        status = self.sh_primary.get_db_cluster_status()
        self.assertIn(self.constant.CLUSTER_NORMAL_MSG, status)
        LOG.info(f'--------{os.path.basename(__file__)} end--------')
